<?php
namespace Common\Model;
use Think\Model;

/**
 * 文章内容model操作
 * @author  singwa
 */
class CategoryModel extends Model {
    private $_db = '';

    public function __construct() {
        $this->_db = M('category');
    }
    public function select($data = array(), $limit = 100) {
        $data['status']=1;
        $conditions = $data;
        $list = $this->_db->where($conditions)->order('id asc')->limit($limit)->select();
        return $list;
    }
    public function insert($data = array()) {
        if(!is_array($data) || !$data) {
            return 0;
        }
        $data['inputtime']  = TIME();
        $data['status']  = 1;
        return $this->_db->add($data);
    }
    public function getcat($data,$page,$pageSize=10) {
        $conditions = $data;
        if(isset($data['title']) && $data['title']) {
            $conditions['catname'] = array('like','%'.$data['title'].'%');
        }
        if(isset($data['id']) && $data['id'])  {
            $conditions['id'] = intval($data['id']);
        }
        $conditions['status'] = array('neq',2);

        $offset = ($page - 1) * $pageSize;
        $list = $this->_db->where($conditions)
            ->order('id desc')
            ->limit($offset,$pageSize)
            ->select();

        return $list;

    }


    public function getcatCount($data = array()){
        $conditions = $data;
        if(isset($data['title']) && $data['title']) {
            $conditions['catname'] = array('like','%'.$data['title'].'%');
        }
        if(isset($data['id']) && $data['id'])  {
            $conditions['id'] = intval($data['id']);
        }
        $conditions['status'] = array('neq',2);

        return $this->_db->where($conditions)->count();

    }

    public function find($id) {
        $data = $this->_db->where('id='.$id)->find();
        return $data;
    }

    public function updateById($id, $data) {
        if(!$id || !is_numeric($id) ) {
            throw_exception("ID不合法");
        }
        if(!$data || !is_array($data)) {
            throw_exception('更新数据不合法');
        }

        return $this->_db->where('id='.$id)->save($data);
    }

    public function updateStatusById($id, $status) {
        if(!is_numeric($status)) {
            throw_exception('status不能为非数字');
        }
        if(!$id || !is_numeric($id)) {
            throw_exception('id不合法');
        }
        $data['status'] = $status;

        return $this->_db->where('id='.$id)->save($data);
    }

    public function updateCateById($id, $data){
        if(!$id || !is_numeric($id)) {
            throw_exception('数据错误');
        }

        if(!$data || !is_array($data)) {
            throw_exception('更新的数据不合法');
        }
        return $this->_db->where('id='.$id)->save($data);
    }
    


}
